package com.lovestudying.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.google.gson.Gson;
import com.lovestudying.entity.Course;
import com.lovestudying.service.CourseService;
import com.lovestudying.service.VideoService;
import com.lovestudying.service.impl.CourseServiceImpl;
import com.lovestudying.service.impl.VideoServiceImpl;
import com.lovestudying.util.DBUtil_Pro;
import com.lovestudying.util.PageInfo;

/**
 * Servlet implementation class CotrseServlet
 */
/**
 * @author OldDeer
 *
 */
@WebServlet("/CourseServletForyd")
@MultipartConfig
public class CourseServletForyd extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CourseService courseService = new CourseServiceImpl();
	VideoService videoService = new VideoServiceImpl();
	Gson gson = new Gson();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CourseServletForyd() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = request.getParameter("op");
		// System.out.println(op);
		if (op != null) {
			switch (op) {
			case "getCourseListByPage":
				doGetCourseListByPage(request, response);
				break;
			case "toSingleCoursePage":
				toSingleCoursePage(request, response);
				break;
			case "getCourseInfoById":
				getCourseInfoById(request, response);
				break;
			case "deleteCourseById":
				doDeleteCourseById(request, response);
				break;
			case "getIntrestedCourse":
				getIntrestedCourse(request, response);
				break;
			case "updateCourseById":
				updateCourseById(request, response);
				break;
			case "addCourse":
				addCourse(request, response);
				break;
			default:
				break;
			}
		}

	}

	private void addCourse(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// TODO 自动生成的方法存根
		// 接收裁剪图片坐标参数
		Integer x = new Double(Double.parseDouble(request.getParameter("pic-x"))).intValue();
		Integer y = new Double(Double.parseDouble(request.getParameter("pic-y"))).intValue();
		Integer destWidth = new Double(Double.parseDouble(request.getParameter("destWidth"))).intValue();
		Integer destHeight = new Double(Double.parseDouble(request.getParameter("destHeight"))).intValue();
		Integer finalWidth = new Double(Double.parseDouble(request.getParameter("finalWidth"))).intValue();
		Integer finalHeight = new Double(Double.parseDouble(request.getParameter("finalHeight"))).intValue();

		// 接收普通组件
		String addTab = request.getParameter("addTab").trim();
		List<String> Tabs = new Vector<>();
		String[] split = addTab.split(" ");
		for (String string : split) {
			// String[] split2 = string.split(";");
			// for (String string2 : split2) {
			Tabs.add(string.trim());
			// }
		}
		String addIntrodu = request.getParameter("addIntrodu");
		String teacherId = request.getParameter("teacherId");
		String addCourseTitle = request.getParameter("addCourseTitle");
		Double addCoursePrice = Double.parseDouble(request.getParameter("addCoursePrice"));
		Integer ResState = 0;
		String courseUuid = DBUtil_Pro.GetUUID();
		String[] parameterValues = request.getParameterValues("addpayType");
		Integer payType = 3;
		if (parameterValues != null && parameterValues.length != 0) {
			payType = Integer.parseInt(parameterValues[0]);
		}
		Part part = request.getPart("facePicture");
		// 判断用户是否有上传文件
		if (part.getSize() == 0) { // 没有上传
			// 业务逻辑层
			// System.out.println("无缩略图添加");
			if (courseService.addCourse(courseUuid, addCourseTitle, addCoursePrice, payType, addIntrodu, null,
					teacherId, Tabs)) {
				ResState = 1;

			}
		} else { // 有上传
			// 允许的文件图片类型
			String allowImgType = "image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));
			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			if (allowImgTypeList.contains(contentType) == false) {
				// 重定向注册页面,提示文件不合法
				System.out.println("文件不合法");
				// response.sendRedirect("front/register.jsp?fileuploaderror=fileuploaderror");
				return;
			} else {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);
				// 随机数
				int random = (int) (Math.random() * 1000 + 1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);
				// 将文件存储在指定服务器中(本地电脑D盘)
				File file = new File("D:\\fileupload\\images\\Courses");
				// 目录如果不存在，则创建
				if (!file.exists()) {
					file.mkdirs();
				}
				if (file.exists()) {
					// 将文件写入指定位置
					String filePath = file.getPath() + File.separator + fileName + fileSuffix;
					part.write(filePath);
					// 重读取并裁剪头像
					DBUtil_Pro.abscut(filePath, x, y, destWidth, destHeight, finalWidth, finalHeight);
				}
				// 调用业务层
				// 数据库中仅需要存储文件名.扩展名
				if (courseService.addCourse(courseUuid, addCourseTitle, addCoursePrice, payType, addIntrodu,
						fileName + fileSuffix, teacherId, Tabs)) {
					ResState = 1;
				}

			}
		}
		// 获取视频文件
		Collection<Part> partV = request.getParts();
		for (Part partVideo : partV) {
			//
			if ("upLoadVideo".equals(partVideo.getName()) && ResState == 1 && partVideo.getSize() != 0) {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = partVideo.getHeader("content-disposition");
				String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				String videoTitle = realName.substring(0, realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);
				// 随机数
				int random = (int) (Math.random() * 1000 + 1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);

				// 将文件存储在指定服务器中(本地电脑D盘)
				File file = new File("D:\\fileupload\\courses\\" + courseUuid);
				// 目录如果不存在，则创建
				if (!file.exists()) {
					file.mkdirs();
				}
				if (file.exists()) {
					// 将文件写入指定位置
					String filePath = file.getPath() + File.separator + fileName + fileSuffix;
					partVideo.write(filePath);
				}
				// 调用业务层
				if (!videoService.addVideo(DBUtil_Pro.GetUUID(), videoTitle, courseUuid, fileName + fileSuffix)) {
					ResState = 2;
				}
				// 数据库中仅需要存储文件名.扩展名
			}
		}
		response.getWriter().print(ResState);

	}

	private void updateCourseById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO 自动生成的方法存根
		String updateCourseTitle = request.getParameter("updateCourseTitle");
		String[] parameterValues = request.getParameterValues("payType");
		Integer payType = null;
		if (parameterValues.length != 0) {
			payType = Integer.parseInt(parameterValues[0]);
		}
		String updateCourseId = request.getParameter("updateCourseId");
		Double updateCoursePrice = Double.parseDouble(request.getParameter("updateCoursePrice"));
		String introdu = request.getParameter("introdu");
		Boolean updateCourseById = courseService.updateCourseById(updateCourseId, updateCourseTitle, payType, introdu,
				updateCoursePrice);
		response.getWriter().print(updateCourseById);

	}

	private void getIntrestedCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO 自动生成的方法存根
		String[] tabs = request.getParameterValues("keyWords");
		// System.out.println(parameterValues);
		List<Course> intrestedCourseByTab = courseService.getIntrestedCourseByTab(tabs);

		response.getWriter().print(gson.toJson(intrestedCourseByTab));

	}

	private void doDeleteCourseById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取课程id
		String courseId = request.getParameter("courseId");
		// 调用业务层
		courseService.DeleteCourseById(courseId);
		doGetCourseListByPage(request, response);
	}

	private void getCourseInfoById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String courseId = request.getParameter("courseId");
		Course course = courseService.getCourseInformationById(courseId);
		String Jcourse = gson.toJson(course);
		response.setContentType("application/json");
		response.getWriter().write(Jcourse);
	}

	private void toSingleCoursePage(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String courseId = request.getParameter("courseId");
		response.sendRedirect("front/course-single.jsp?courseId=" + courseId);
	}

	private void doGetCourseListByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String courseTitle = request.getParameter("courseTitle");
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		Map<String, String> map = new HashMap<>();
		map.put("courseTitle", courseTitle);
		map.put("pageNum", pageNum);
		map.put("pageSize", pageSize);
		PageInfo<Course> courseInformation = courseService.getCourseInformationByTab(map);

		String json = gson.toJson(courseInformation);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}

}
